package com.da.lon.wang.xlg.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.AutoLoginBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.constants.XLGConstants.MethodName;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import java.io.File;

/**
 * 升级
 */
public class UpdataActivity extends BaseActivity implements OnClickListener {

    boolean flag = false;
    private String url = "";
    private ProgressBar pb;
    private TextView size;
    private int barsize = 0;
    private Button cancle, sure;
    private TextView des;
    private String desContent = "";
    private String versionName = "";
    private TextView title;
    private String versionCode = "0";
    private String isForced;
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    gotoHome();
                    break;
                default:
                    break;
            }
        }

        ;

    };

    @Override
    protected void onResume() {
        super.onResume();
        sure.setEnabled(true);
        cancle.setEnabled(true);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.xlg_updata);
            url = getIntent().getStringExtra("url");
            desContent = getIntent().getStringExtra("des");
            versionName = getIntent().getStringExtra("versionName");
            versionCode = getIntent().getStringExtra("versionCode");
            isForced = getIntent().getStringExtra("isForced");
            initView();
            PackageInfo packageInfo = getPackageManager().getPackageInfo(
                    getPackageName(), 0);
            int verCode = packageInfo.versionCode;
            if (versionCode != null && !"null".equals(versionCode)
                    && !versionCode.trim().isEmpty()
                    && !isForced.trim().equals("") && isForced.equals("1")) {
                //强制升级
                cancle.setVisibility(View.GONE);
            } else if ((Integer.parseInt(versionCode) - verCode) > 2) {
                //线上和本地版本相差2个版本，也强制升级
                cancle.setVisibility(View.GONE);
            } else {
                cancle.setVisibility(View.VISIBLE);
            }
            title.setText("新版本 : " + versionName);
            if (!TextUtils.isEmpty(desContent)) {
                des.setText("更新内容:" + "\n\n" + desContent);
            }
            if (isFileDownLoad()) {
                sure.setText("马上安装");
                size.setText("您已完成下载，是否马上安装？");
                size.setGravity(Gravity.CENTER);
            } else {
                sure.setText("立即升级");
                size.setText("");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        title = (TextView) findViewById(R.id.title);
        pb = (ProgressBar) findViewById(R.id.show_schedule);
        size = (TextView) findViewById(R.id.size);
        cancle = (Button) findViewById(R.id.cancle);
        sure = (Button) findViewById(R.id.sure);
        cancle.setOnClickListener(this);
        sure.setOnClickListener(this);
        des = (TextView) findViewById(R.id.des);

    }

    /**
     * 下载APK
     */
    public void downLoadThing() {
        try {
            pb.setVisibility(View.VISIBLE);
            final String sdpath = getSDPath();
            FinalHttp fh = new FinalHttp();
            fh.download(url, sdpath, flag, new AjaxCallBack<File>() {
                @Override
                public void onLoading(long count, long current) {
                    barsize = (int) (current * 100 / count);
                    size.setText("下载进度：" + barsize + "%");
                    pb.setProgress(barsize);
                    if (barsize == 100) {
                        flag = false;
                    }
                }

                @Override
                public void onSuccess(File t) {
                    sure.setEnabled(true);
                    cancle.setEnabled(true);
                    size.setText("下载完成");
                    sure.setText("马上安装");
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    sure.setEnabled(true);
                    cancle.setEnabled(true);
                    size.setText("下载失败");
                    sure.setText("重新下载");
                    File file = new File(sdpath);
                    if (file.exists()) {
                        file.delete();
                    }
                    super.onFailure(t, errorNo, strMsg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取文件路径
     */
    public String getSDPath() {
        String savePathString = null;
        try {
            String savePAth = Environment.getExternalStorageDirectory()
                    + XLGConstants.FILE_PAHT;
            File file1 = new File(savePAth);
            if (!file1.exists()) {
                file1.mkdir();
            }
            savePathString = Environment.getExternalStorageDirectory()
                    + XLGConstants.FILE_PAHT + XLGConstants.FILE_PAHT + "-"
                    + versionName + ".apk";
            File file2 = new File(savePathString);
            if (file2.exists()) {
                file2.delete();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return savePathString;
    }

    /**
     * 判断文件是否已经下载
     */

    private boolean isFileDownLoad() {
        String savePathString = Environment.getExternalStorageDirectory()
                + XLGConstants.FILE_PAHT + XLGConstants.FILE_PAHT + "-"
                + versionName + ".apk";
        File file2 = new File(savePathString);
        if (file2.exists()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        } else {
            return false;
        }
    }

    private void installFile(String str) {
        String fileName = Environment.getExternalStorageDirectory() + str;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(fileName)),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sure:
                if (sure.getText().toString().equals("立即升级")) {
                    downLoadThing();
                } else if (sure.getText().toString().equals("马上安装")) {
                    String str = XLGConstants.FILE_PAHT + XLGConstants.FILE_PAHT
                            + "-" + versionName + ".apk";
                    installFile(str);
                } else if (sure.getText().toString().equals("重新下载")) {
                    downLoadThing();
                }
                sure.setEnabled(false);
                cancle.setEnabled(false);
                break;
            case R.id.cancle:
                checkUserName();
                MyApplication.clearActivityList();
                break;
            default:
                break;
        }

    }

    /**
     * 检查用户名是否过期
     */
    private void checkUserName() {
        if (TextUtils.isEmpty(MyApplication.getUserKey())) {
            handler.sendEmptyMessageDelayed(1, 1000);
        } else {
            autoLogin();
        }
    }

    /**
     * 自动登录
     */

    private void autoLogin() {
        try {
            String url = XLGConstants.URL + XLGConstants.URL_HEAD
                    + MethodName.AUTOLOGIN;
            HttpLoader<AutoLoginBean> httpLoader = new HttpLoader<AutoLoginBean>(
                    this, url, AutoLoginBean.class);
            AjaxParams params = new AjaxParams();
            params.put(
                    "user_key",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_KEY, ""));
            params.put(
                    "user_id",
                    PreferenceUtils.getInstance().getSettingStr(
                            PreferencesConfig.USER_ID, ""));
            params.put("device_type", "1");
            params.put(
                    "token",
                    XLGDataUtils.encrypt2MD5(XLGConstants.API
                            + XLGConstants.SECRET + MethodName.AUTOLOGIN));
            httpLoader
                    .setManagerListener(new OnWebLoadListener<AutoLoginBean>() {

                        @Override
                        public void OnStart() {

                        }

                        @Override
                        public void OnError(String error) {
                            // showNetError(UpdataActivity.this);
                        }

                        @Override
                        public void onSuccess(AutoLoginBean t) {
                            dismissDialog();
                            if (t != null && t.getCode().equals("000000")) {
                                PreferenceUtils.getInstance().SetSettingString(
                                        PreferencesConfig.USER_KEY,
                                        t.getResult().user_key);
                                if (t.getResult().getStore_id() != null) {
                                    PreferenceUtils
                                            .getInstance()
                                            .SetSettingString(
                                                    PreferencesConfig.STORE_ID,
                                                    t.getResult().getStore_id());
                                    PreferenceUtils
                                            .getInstance()
                                            .SetSettingString(
                                                    PreferencesConfig.STORE_NAME,
                                                    t.getResult()
                                                            .getStore_name());
                                }
                            } else {
                                PreferenceUtils.getInstance().SetSettingString(
                                        PreferencesConfig.USER_KEY, "");
                                PreferenceUtils.getInstance().SetSettingString(
                                        PreferencesConfig.USER_ID, "");
                                PreferenceUtils.getInstance().SetSettingString(
                                        PreferencesConfig.STORE_ID, "");
                                PreferenceUtils.getInstance().SetSettingString(
                                        PreferencesConfig.STORE_NAME, "");
                                Tencent tencent = Tencent.createInstance(
                                        XLGConstants.APP_ID,
                                        UpdataActivity.this);
                                if (tencent != null) {
                                    tencent.logout(UpdataActivity.this);
                                    tencent.releaseResource();
                                }
                            }
                            handler.sendEmptyMessageDelayed(1, 1 * 1000);
                        }
                    });

            httpLoader.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 跳转到首页
     */
    private void gotoHome() {

        boolean isFirst = PreferenceUtils.getInstance().getSettingBool(
                "is_first", false);

        if (!isFirst) {
            Intent guideIntent = new Intent(UpdataActivity.this,
                    GuideActivity.class);
            startActivity(guideIntent);
            PreferenceUtils.getInstance().SetSettingBoolean("is_first", true);
        } else {
            Intent intent = null;
//			if ("".equals(MyApplication.getShopId())) {
//				intent = new Intent(UpdataActivity.this,
//						ChoessSKUListActivity.class);
//			} else {
            intent = new Intent(UpdataActivity.this, HomeActivity.class);
//			}
            startActivity(intent);
        }
        finish();
    }
}
